package aliyun.cx.admin.controller;

import aliyun.cx.admin.entity.User;
import aliyun.cx.admin.entity.Role;
import aliyun.cx.admin.entity.Permission;
import aliyun.cx.admin.service.UserService;
import aliyun.cx.admin.service.RoleService;
import aliyun.cx.admin.service.PermissionService;
import aliyun.cx.admin.service.UserRoleService;
import aliyun.cx.admin.util.ConfigUtil;
import aliyun.cx.admin.util.JwtTokenProvider;
import aliyun.cx.common.util.ResponseUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * 管理模块控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*", maxAge = 3600)
public class AdminController {
    
    private final UserService userService;
    
    private final RoleService roleService;
    
    private final PermissionService permissionService;
    
    private final UserRoleService userRoleService;
    
    private final ConfigUtil configUtil;
    
    private final JwtTokenProvider jwtTokenProvider;
    
    private final PasswordEncoder passwordEncoder;

    public AdminController(UserService userService, RoleService roleService, PermissionService permissionService, UserRoleService userRoleService, ConfigUtil configUtil, JwtTokenProvider jwtTokenProvider, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.roleService = roleService;
        this.permissionService = permissionService;
        this.userRoleService = userRoleService;
        this.configUtil = configUtil;
        this.jwtTokenProvider = jwtTokenProvider;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从数据库查询用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            User user = userService.getOne(queryWrapper);
            
            if (user != null && user.getEnabled() == 1) {
                // 验证密码
                if (passwordEncoder.matches(password, user.getPassword())) {
                    // 创建UserDetails对象用于JWT生成
                    UserDetails userDetails = org.springframework.security.core.userdetails.User.builder()
                            .username(user.getUsername())
                            .password(user.getPassword())
                            .authorities("USER")
                            .build();
                    
                    // 生成JWT token
                    String accessToken = jwtTokenProvider.generateToken(userDetails, user.getId());
                    String refreshToken = jwtTokenProvider.generateRefreshToken(userDetails, user.getId());
                    
                    result.put("code", 200);
                    result.put("message", "登录成功");
                    
                    Map<String, Object> userData = new HashMap<>();
                    userData.put("id", user.getId());
                    userData.put("username", user.getUsername());
                    userData.put("nickname", user.getNickname());
                    userData.put("email", user.getEmail());
                    userData.put("avatar_url", user.getAvatarUrl());
                    
                    Map<String, Object> data = new HashMap<>();
                    data.put("token", accessToken);
                    data.put("refreshToken", refreshToken);
                    data.put("user", userData);
                    data.put("expiresIn", jwtTokenProvider.getTokenExpirationTime(accessToken));
                    
                    result.put("data", data);
                } else {
                    result.put("code", 401);
                    result.put("message", "用户名或密码错误");
                }
            } else {
                result.put("code", 401);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "登录失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Map<String, Object> logout() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登出成功");
        return result;
    }
    
    /**
     * 刷新Token
     */
    @PostMapping("/refresh-token")
    public Map<String, Object> refreshToken(@RequestBody Map<String, String> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String refreshToken = request.get("refreshToken");
            if (refreshToken == null || refreshToken.isEmpty()) {
                result.put("code", 400);
                result.put("message", "Refresh token不能为空");
                return result;
            }
            
            // 验证并刷新token
            String newAccessToken = jwtTokenProvider.refreshToken(refreshToken);
            
            result.put("code", 200);
            result.put("message", "Token刷新成功");
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", newAccessToken);
            data.put("expiresIn", jwtTokenProvider.getTokenExpirationTime(newAccessToken));
            
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 401);
            result.put("message", "Token刷新失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取当前用户信息
     */
    @GetMapping("/user/info")
    public Map<String, Object> getCurrentUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从请求头中提取JWT token
            String jwt = getJwtFromRequest(token);
            if (jwt == null || !jwtTokenProvider.validateToken(jwt)) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            // 从本地解析用户信息（因为Security过滤器已经验证过）
            Long userId = jwtTokenProvider.getUserIdFromToken(jwt);

            // 从数据库查询用户信息
            User user = userService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 获取用户角色和权限（使用新的权限管理服务）
            List<Role> userRoles = roleService.getRolesByUserId(user.getId());
            List<Permission> userPermissions = permissionService.getPermissionsByUserId(user.getId());
                            
            String[] roles = userRoles.stream()
                .map(Role::getName)
                .toArray(String[]::new);
            String[] permissions = userPermissions.stream()
                .map(Permission::getName) 
                .toArray(String[]::new);
            
            Map<String, Object> userData = new HashMap<>();
            userData.put("id", user.getId());
            userData.put("username", user.getUsername());
            userData.put("nickname", user.getNickname());
            userData.put("email", user.getEmail());
            userData.put("avatar_url", user.getAvatarUrl());
            
            Map<String, Object> data = new HashMap<>();
            data.put("user", userData);
            data.put("roles", roles);
            data.put("permissions", permissions);
            data.put("tokenExpiration", jwtTokenProvider.getTokenExpirationTime(jwt));
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取用户信息失败：" + e.getMessage());
        }
        
        return result;
    }



    /**
     * 从请求头中提取JWT token
     */
    private String getJwtFromRequest(String authHeader) {
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
    
    /**
     * 获取用户列表
     */
    @GetMapping("/users")
    public Map<String, Object> getUserList(@RequestParam(defaultValue = "1") Integer current,
                                          @RequestParam(defaultValue = "10") Integer size) {
        Page<User> page = new Page<>(current, size);
        // 查询所有用户，包括启用和禁用的
        Page<User> userPage = userService.page(page, new QueryWrapper<>());
        
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "success");
        result.put("data", userPage);
        return result;
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/users/{id}")
    public Map<String, Object> getUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        
        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", user);
        } else {
            result.put("code", 404);
            result.put("message", "用户不存在");
        }
        return result;
    }
    
    /**
     * 创建用户
     */
    @PostMapping("/users")
    public Map<String, Object> createUser(@RequestBody User user) {
        try {
            // 检查用户注册功能是否启用
            if (!configUtil.isUserRegisterEnabled()) {
                return ResponseUtil.error(403, "用户注册功能已禁用");
            }
            
            // 检查用户名是否已存在
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 400);
                result.put("message", "用户名已存在");
                return result;
            }
            
            // 加密密码
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            
            // 设置默认头像
            if (user.getAvatarUrl() == null || user.getAvatarUrl().isEmpty()) {
                user.setAvatarUrl("https://api.dicebear.com/7.x/avataaars/svg?seed=" + user.getUsername());
            }
            
            boolean success = userService.save(user);
            return ResponseUtil.userCreateResult(success, user);
        } catch (Exception e) {
            return ResponseUtil.error("创建失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户
     */
    @PutMapping("/users/{id}")
    public Map<String, Object> updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        boolean success = userService.updateById(user);
        return ResponseUtil.userUpdateResult(success, user);
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/users/{id}")
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        boolean success = userService.removeById(id);
        return ResponseUtil.userDeleteResult(success);
    }
    
    /**
     * 获取个人资料
     */
    @GetMapping("/profile")
    public Map<String, Object> getProfile(@RequestHeader(value = "Authorization", required = false) String token) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从请求头中提取JWT token
            String jwt = getJwtFromRequest(token);
            if (jwt == null || !jwtTokenProvider.validateToken(jwt)) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            Long userId = jwtTokenProvider.getUserIdFromToken(jwt);
            
            User user = userService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 返回个人资料信息（不包含密码）
            Map<String, Object> profileData = new HashMap<>();
            profileData.put("id", user.getId());
            profileData.put("username", user.getUsername());
            profileData.put("nickname", user.getNickname());
            profileData.put("email", user.getEmail());
            profileData.put("avatar_url", user.getAvatarUrl());
            profileData.put("enabled", user.getEnabled());
            profileData.put("account_non_locked", user.getAccountNonLocked());
            profileData.put("credentials_non_expired", user.getCredentialsNonExpired());
            profileData.put("create_time", user.getCreateTime());
            profileData.put("update_time", user.getUpdateTime());
            
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", profileData);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取个人资料失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 更新个人资料
     */
    @PutMapping("/profile")
    public Map<String, Object> updateProfile(@RequestHeader(value = "Authorization", required = false) String token,
                                            @RequestBody Map<String, Object> profileData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从请求头中提取JWT token
            String jwt = getJwtFromRequest(token);
            if (jwt == null || !jwtTokenProvider.validateToken(jwt)) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            Long userId = jwtTokenProvider.getUserIdFromToken(jwt);
            
            User user = userService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 只允许更新特定字段
            if (profileData.containsKey("nickname")) {
                user.setNickname((String) profileData.get("nickname"));
            }
            if (profileData.containsKey("email")) {
                user.setEmail((String) profileData.get("email"));
            }
            if (profileData.containsKey("avatar_url")) {
                user.setAvatarUrl((String) profileData.get("avatar_url"));
            }
            
            boolean success = userService.updateById(user);
            if (success) {
                // 返回更新后的用户信息（不包含密码）
                Map<String, Object> updatedProfile = new HashMap<>();
                updatedProfile.put("id", user.getId());
                updatedProfile.put("username", user.getUsername());
                updatedProfile.put("nickname", user.getNickname());
                updatedProfile.put("email", user.getEmail());
                updatedProfile.put("avatar_url", user.getAvatarUrl());
                updatedProfile.put("enabled", user.getEnabled());
                updatedProfile.put("account_non_locked", user.getAccountNonLocked());
                updatedProfile.put("credentials_non_expired", user.getCredentialsNonExpired());
                updatedProfile.put("create_time", user.getCreateTime());
                updatedProfile.put("update_time", user.getUpdateTime());
                
                result.put("code", 200);
                result.put("message", "更新成功");
                result.put("data", updatedProfile);
            } else {
                result.put("code", 500);
                result.put("message", "更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新个人资料失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/profile/avatar")
    public Map<String, Object> uploadAvatar(@RequestHeader(value = "Authorization", required = false) String token,
                                           @RequestParam("avatar") String avatarUrl) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 从请求头中提取JWT token
            String jwt = getJwtFromRequest(token);
            if (jwt == null || !jwtTokenProvider.validateToken(jwt)) {
                result.put("code", 401);
                result.put("message", "无效的token");
                return result;
            }
            
            Long userId = jwtTokenProvider.getUserIdFromToken(jwt);
            
            User user = userService.getById(userId);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 更新头像URL
            user.setAvatarUrl(avatarUrl);
            boolean success = userService.updateById(user);
            
            if (success) {
                // 返回更新后的完整用户信息（不包含密码）
                Map<String, Object> updatedProfile = new HashMap<>();
                updatedProfile.put("id", user.getId());
                updatedProfile.put("username", user.getUsername());
                updatedProfile.put("nickname", user.getNickname());
                updatedProfile.put("email", user.getEmail());
                updatedProfile.put("avatar_url", user.getAvatarUrl());
                updatedProfile.put("enabled", user.getEnabled());
                updatedProfile.put("account_non_locked", user.getAccountNonLocked());
                updatedProfile.put("credentials_non_expired", user.getCredentialsNonExpired());
                updatedProfile.put("create_time", user.getCreateTime());
                updatedProfile.put("update_time", user.getUpdateTime());
                
                result.put("code", 200);
                result.put("message", "头像更新成功");
                result.put("data", updatedProfile);
            } else {
                result.put("code", 500);
                result.put("message", "头像更新失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "头像上传失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取用户的角色列表（API接口）
     */
    @GetMapping("/users/{id}/roles")
    public Map<String, Object> getUserRoleList(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Role> roles = roleService.getRolesByUserId(id);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", roles);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取用户角色失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 为用户分配角色
     */
    @PostMapping("/users/{id}/roles")
    public Map<String, Object> assignUserRoles(@PathVariable Long id, @RequestBody Map<String, List<Long>> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            User user = userService.getById(id);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            List<Long> roleIds = request.get("roleIds");
            boolean success = userRoleService.assignRoles(id, roleIds);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "角色分配成功");
            } else {
                result.put("code", 500);
                result.put("message", "角色分配失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "分配用户角色失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 移除用户的角色
     */
    @DeleteMapping("/users/{id}/roles")
    public Map<String, Object> removeUserRoles(@PathVariable Long id, @RequestBody Map<String, List<Long>> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            User user = userService.getById(id);
            if (user == null) {
                result.put("code", 404);
                result.put("message", "用户不存在");
                return result;
            }
            
            List<Long> roleIds = request.get("roleIds");
            boolean success = userRoleService.removeRoles(id, roleIds);
            
            if (success) {
                result.put("code", 200);
                result.put("message", "角色移除成功");
            } else {
                result.put("code", 500);
                result.put("message", "角色移除失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "移除用户角色失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取用户的权限列表（API接口）
     */
    @GetMapping("/users/{id}/permissions")
    public Map<String, Object> getUserPermissionList(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Permission> permissions = permissionService.getPermissionsByUserId(id);
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", permissions);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取用户权限失败：" + e.getMessage());
        }
        
        return result;
    }
}
